import SwiftUI

struct HomeView: View {
    @StateObject var viewModel = HomeViewModel()
    
    // 预设的饮水量选项
    let waterOptions: [Double] = [200, 300, 500]
    
    // 自定义饮水量输入
    @State private var showingCustomAmountSheet = false
    @State private var customAmount: String = ""
    
    // 动画相关状态
    @State private var waveOffset = Angle(degrees: 0)
    @State private var waveHeight: CGFloat = 0.3
    
    // 显示记录历史
    @State private var showingHistory = false
    
    var body: some View {
        VStack(spacing: 20) {
            // 顶部标题和健康提示
            VStack(spacing: 10) {
                Text("每日饮水")
                    .font(.largeTitle)
                    .fontWeight(.bold)
                
                Text(viewModel.getDailyHealthTip())
                    .font(.subheadline)
                    .foregroundColor(.secondary)
                    .multilineTextAlignment(.center)
                    .padding(.horizontal)
            }
            
            // 进度指示器和水波动画
            ZStack {
                // 水杯背景
                Circle()
                    .stroke(Color.blue.opacity(0.2), lineWidth: 20)
                    .frame(width: 220, height: 220)
                
                // 水波动画
                WaveView(offset: waveOffset, percent: viewModel.progress)
                    .frame(width: 180, height: 180)
                    .clipShape(Circle())
                
                // 进度环
                Circle()
                    .trim(from: 0, to: CGFloat(viewModel.progress))
                    .stroke(Color.blue, style: StrokeStyle(lineWidth: 20, lineCap: .round))
                    .frame(width: 220, height: 220)
                    .rotationEffect(.degrees(-90))
                    .animation(.easeInOut(duration: 1.0), value: viewModel.progress)
                
                // 中间的文字
                VStack {
                    Text("\(Int(viewModel.todayTotal))毫升")
                        .font(.system(size: 28, weight: .bold))
                    
                    Text("目标: \(Int(viewModel.userProfile.goal))毫升")
                        .font(.subheadline)
                        .foregroundColor(.secondary)
                }
            }
            .padding(.vertical, 10)
            .onAppear {
                // 启动水波动画
                withAnimation(Animation.linear(duration: 2).repeatForever(autoreverses: false)) {
                    self.waveOffset = Angle(degrees: 360)
                }
            }
            
            // 剩余饮水量和进度指示
            VStack(spacing: 10) {
                if !viewModel.hasReachedGoal() {
                    Text("还需饮水\(Int(viewModel.getRemainingAmount()))毫升")
                        .font(.headline)
                        .foregroundColor(.secondary)
                    
                    // 进度条
                    ProgressView(value: viewModel.progress)
                        .progressViewStyle(LinearProgressViewStyle(tint: Color.blue))
                        .padding(.horizontal)
                } else {
                    Text("今日目标已达成！")
                        .font(.headline)
                        .foregroundColor(.green)
                    
                    // 奖励徽章
                    Image(systemName: "medal.fill")
                        .font(.system(size: 36))
                        .foregroundColor(.yellow)
                        .padding(.top, 8)
                }
            }
            
            // 饮水记录按钮
            VStack(spacing: 16) {
                Text("添加饮水量")
                    .font(.headline)
                
                HStack(spacing: 15) {
                    ForEach(waterOptions, id: \.self) { amount in
                        Button(action: {
                            viewModel.recordWaterIntake(amount: amount)
                            playAddWaterAnimation()
                        }) {
                            VStack {
                                Image(systemName: "drop.fill")
                                    .font(.title2)
                                Text("\(Int(amount))毫升")
                                    .font(.caption)
                            }
                            .foregroundColor(.white)
                            .frame(width: 70, height: 70)
                            .background(Color.blue)
                            .cornerRadius(15)
                        }
                    }
                    
                    // 自定义饮水量按钮
                    Button(action: {
                        showingCustomAmountSheet = true
                    }) {
                        VStack {
                            Image(systemName: "plus")
                                .font(.title2)
                            Text("自定义")
                                .font(.caption)
                        }
                        .foregroundColor(.white)
                        .frame(width: 70, height: 70)
                        .background(Color.blue.opacity(0.7))
                        .cornerRadius(15)
                    }
                }
            }
            .padding(.top, 10)
            
            // 最近饮水记录
            VStack(alignment: .leading, spacing: 8) {
                HStack {
                    Text("今日饮水记录")
                        .font(.headline)
                    
                    Spacer()
                    
                    Button(action: {
                        showingHistory = true
                    }) {
                        Text("查看更多")
                            .font(.caption)
                            .foregroundColor(.blue)
                    }
                }
                .padding(.horizontal)
                
                ScrollView(.horizontal, showsIndicators: false) {
                    HStack(spacing: 15) {
                        ForEach(viewModel.getTodayRecords().prefix(5), id: \.id) { record in
                            VStack(spacing: 5) {
                                Text("\(Int(record.amount))毫升")
                                    .font(.system(size: 16, weight: .bold))
                                
                                Text(formatTime(record.date))
                                    .font(.caption)
                                    .foregroundColor(.secondary)
                            }
                            .padding(.vertical, 8)
                            .padding(.horizontal, 12)
                            .background(Color.blue.opacity(0.1))
                            .cornerRadius(10)
                        }
                    }
                    .padding(.horizontal)
                }
                .frame(height: 60)
            }
            
            Spacer()
            
            // 下次提醒时间
            HStack {
                Image(systemName: "bell.fill")
                    .foregroundColor(.orange)
                
                Text("下次提醒")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
                
                Text("1小时后") // 这里将来会实现动态计算
                    .font(.headline)
            }
            .padding(.bottom, 20)
        }
        .padding()
        .sheet(isPresented: $showingCustomAmountSheet) {
            CustomAmountInputView(isPresented: $showingCustomAmountSheet, customAmount: $customAmount) { amount in
                if let amountValue = Double(amount), amountValue > 0 {
                    viewModel.recordWaterIntake(amount: amountValue)
                    playAddWaterAnimation()
                }
            }
        }
        .sheet(isPresented: $showingHistory) {
            WaterHistoryView(viewModel: viewModel)
        }
    }
    
    // 播放添加水的动画效果
    private func playAddWaterAnimation() {
        // 这里可以添加更丰富的动画逻辑
        withAnimation(.spring()) {
            // 暂时的动画效果，可以扩展更多
        }
    }
    
    // 格式化时间为"HH:mm"
    private func formatTime(_ date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm"
        return formatter.string(from: date)
    }
}

// 水波动画视图
struct WaveView: View {
    var offset: Angle
    var percent: Double
    
    var body: some View {
        GeometryReader { geometry in
            ZStack {
                // 第一层波浪 - 深色
                wave(geometry: geometry, amplitude: 10, offset: offset)
                    .fill(Color.blue.opacity(0.5))
                
                // 第二层波浪 - 浅色，相位差
                wave(geometry: geometry, amplitude: 15, offset: offset + Angle(degrees: 180))
                    .fill(Color.blue.opacity(0.3))
            }
            .offset(y: geometry.size.height * (1 - CGFloat(percent)))
        }
    }
    
    func wave(geometry: GeometryProxy, amplitude: CGFloat, offset: Angle) -> Path {
        let width = geometry.size.width
        let height = geometry.size.height
        let midHeight = height / 2
        
        var path = Path()
        path.move(to: CGPoint(x: 0, y: midHeight))
        
        for x in stride(from: 0, to: width, by: 5) {
            let relativeX = x / width
            let sine = sin(Double(relativeX) * 2 * .pi + offset.radians)
            let y = midHeight + CGFloat(sine) * amplitude
            path.addLine(to: CGPoint(x: x, y: y))
        }
        
        path.addLine(to: CGPoint(x: width, y: midHeight))
        path.addLine(to: CGPoint(x: width, y: height))
        path.addLine(to: CGPoint(x: 0, y: height))
        path.closeSubpath()
        
        return path
    }
}

// 自定义饮水量输入视图
struct CustomAmountInputView: View {
    @Binding var isPresented: Bool
    @Binding var customAmount: String
    var onSubmit: (String) -> Void
    
    // 添加推荐饮水量选项
    let recommendedOptions = [50, 100, 150, 250, 330, 500]
    
    var body: some View {
        NavigationStack {
            VStack(spacing: 20) {
                Text("输入饮水量")
                    .font(.headline)
                
                TextField("饮水量（毫升）", text: $customAmount)
                    .keyboardType(.numberPad)
                    .padding()
                    .background(Color(.systemGray6))
                    .cornerRadius(8)
                    .padding(.horizontal)
                
                // 常用容器大小提示
                Text("常用容器大小")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
                
                // 快速选择按钮，使用更多选项
                LazyVGrid(columns: [
                    GridItem(.flexible()),
                    GridItem(.flexible()),
                    GridItem(.flexible())
                ], spacing: 10) {
                    ForEach(recommendedOptions, id: \.self) { value in
                        Button(action: {
                            customAmount = "\(value)"
                        }) {
                            VStack(spacing: 5) {
                                Text("\(value)")
                                    .fontWeight(.medium)
                                
                                // 添加容器图标
                                Image(systemName: containerIcon(for: value))
                                    .font(.caption)
                            }
                            .frame(maxWidth: .infinity)
                            .padding(.vertical, 8)
                            .background(Color.blue.opacity(0.1))
                            .cornerRadius(8)
                        }
                    }
                }
                .padding(.horizontal)
                
                Button("确认") {
                    onSubmit(customAmount)
                    customAmount = ""
                    isPresented = false
                }
                .foregroundColor(.white)
                .padding()
                .frame(width: 150)
                .background(Color.blue)
                .cornerRadius(10)
                .padding(.top, 10)
            }
            .padding()
            .toolbar {
                ToolbarItem(placement: .topBarTrailing) {
                    Button("取消") {
                        isPresented = false
                    }
                }
            }
        }
        .presentationDetents([.medium])
    }
    
    // 根据容量选择合适的图标
    private func containerIcon(for amount: Int) -> String {
        switch amount {
        case let x where x < 100:
            return "cup.and.saucer.fill"
        case let x where x < 300:
            return "mug.fill"
        case let x where x < 400:
            return "takeoutbag.and.cup.and.straw.fill"
        default:
            return "waterbottle.fill"
        }
    }
}

// 饮水历史记录视图
struct WaterHistoryView: View {
    @ObservedObject var viewModel: HomeViewModel
    @Environment(\.dismiss) private var dismiss
    
    @State private var selectedRange = 0
    private let rangeOptions = ["今天", "昨天", "本周", "本月"]
    
    var body: some View {
        NavigationStack {
            VStack {
                // 时间范围选择
                Picker("时间范围", selection: $selectedRange) {
                    ForEach(0..<rangeOptions.count, id: \.self) { index in
                        Text(rangeOptions[index]).tag(index)
                    }
                }
                .pickerStyle(SegmentedPickerStyle())
                .padding()
                
                // 历史记录列表
                List {
                    ForEach(getFilteredRecords()) { record in
                        HStack {
                            VStack(alignment: .leading) {
                                Text(formatTime(record.date))
                                    .font(.headline)
                                
                                Text(formatDate(record.date))
                                    .font(.caption)
                                    .foregroundColor(.secondary)
                            }
                            
                            Spacer()
                            
                            Text("\(Int(record.amount))毫升")
                                .font(.title3)
                                .fontWeight(.bold)
                                .foregroundColor(.blue)
                        }
                        .padding(.vertical, 5)
                    }
                }
                
                // 汇总信息
                VStack(spacing: 8) {
                    Text("总计: \(Int(getTotalAmount()))毫升")
                        .font(.headline)
                    
                    Text("平均每次: \(getAverageAmount())毫升")
                        .font(.subheadline)
                        .foregroundColor(.secondary)
                }
                .padding()
                .frame(maxWidth: .infinity)
                .background(Color(.systemGray6))
            }
            .navigationTitle("饮水历史记录")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .topBarTrailing) {
                    Button("关闭") {
                        dismiss()
                    }
                }
            }
        }
    }
    
    // 根据选择的时间范围过滤记录
    private func getFilteredRecords() -> [WaterIntake] {
        let calendar = Calendar.current
        let today = calendar.startOfDay(for: Date())
        
        switch selectedRange {
        case 0: // 今天
            return viewModel.waterIntakeStore.intakes.filter {
                calendar.isDate($0.date, inSameDayAs: today)
            }.sorted { $0.date > $1.date }
            
        case 1: // 昨天
            if let yesterday = calendar.date(byAdding: .day, value: -1, to: today) {
                return viewModel.waterIntakeStore.intakes.filter {
                    calendar.isDate($0.date, inSameDayAs: yesterday)
                }.sorted { $0.date > $1.date }
            }
            
        case 2: // 本周
            let weekStart = calendar.date(from: calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: today))!
            return viewModel.waterIntakeStore.intakes.filter {
                $0.date >= weekStart && $0.date < calendar.date(byAdding: .day, value: 7, to: weekStart)!
            }.sorted { $0.date > $1.date }
            
        case 3: // 本月
            let monthStart = calendar.date(from: calendar.dateComponents([.year, .month], from: today))!
            let nextMonth = calendar.date(byAdding: .month, value: 1, to: monthStart)!
            return viewModel.waterIntakeStore.intakes.filter {
                $0.date >= monthStart && $0.date < nextMonth
            }.sorted { $0.date > $1.date }
            
        default:
            return []
        }
        
        return []
    }
    
    // 计算总饮水量
    private func getTotalAmount() -> Double {
        return getFilteredRecords().reduce(0) { $0 + $1.amount }
    }
    
    // 计算平均每次饮水量
    private func getAverageAmount() -> String {
        let records = getFilteredRecords()
        guard !records.isEmpty else { return "0" }
        let average = getTotalAmount() / Double(records.count)
        return String(format: "%.0f", average)
    }
    
    // 格式化时间
    private func formatTime(_ date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm:ss"
        return formatter.string(from: date)
    }
    
    // 格式化日期
    private func formatDate(_ date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter.string(from: date)
    }
} 